package kr.hkit.androidcomplete02.ch17;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

public class SaveState extends Activity {
	MyView mv;
	final static String TAG = "SAVESTATE";
	int count;

	public void onConfigurationChanged(Configuration newConfig) {
		Log.d(TAG, "onConfigurationChanged()");
		super.onConfigurationChanged(newConfig);
		setTitle("Count : " + count++);
	}
	
	protected void onCreate(Bundle savedInstanceState) {
		Log.d(TAG, "onCreate()");
		super.onCreate(savedInstanceState);
		
		ApplicationEx app = (ApplicationEx) getApplication();
		Toast.makeText(this, "전역정보 " + app.getmMode(), Toast.LENGTH_SHORT).show();

		mv = new MyView(this);

		if (savedInstanceState == null) {
			mv.x = 50;
		} else {
			mv.x = savedInstanceState.getInt("x");
		}

		SharedPreferences pref = getSharedPreferences("SaveState", MODE_PRIVATE);
		mv.y = pref.getInt("y", 50);
		
		mv.setFocusable(true);
		mv.setFocusableInTouchMode(true);
		setContentView(mv);
	}
	
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		Log.d(TAG, "onRestoreInstanceState()");
		super.onRestoreInstanceState(savedInstanceState);
	}

	protected void onStart() {
		Log.d(TAG, "onStart()");
		super.onStart();
	}
	
	protected void onResume() {
		Log.d(TAG, "onResume()");
		super.onResume();
	}
	
	protected void onPause() {
		Log.d(TAG, "onPause()");
		super.onPause();
		SharedPreferences pref = getSharedPreferences("SaveState", MODE_PRIVATE);
		SharedPreferences.Editor edit = pref.edit();
		edit.putInt("y", mv.y);
		edit.commit();
	}
	
	protected void onStop() {
		Log.d(TAG, "onStop()");
		super.onStop();
	}
	
	protected void onDestroy() {
		Log.d(TAG, "onDestroy()");
		super.onDestroy();
	}

	protected void onSaveInstanceState(Bundle outState) {
		Log.d(TAG, "onSaveInstanceState()");
		super.onSaveInstanceState(outState);
		outState.putInt("x", mv.x);
	}

}

class MyView extends View {
	Paint p;
	int x;
	int y;

	public MyView(Context context) {
		super(context);
		p = new Paint(Paint.ANTI_ALIAS_FLAG);
	}

	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		p.setColor(Color.GREEN);
		canvas.drawCircle(x, y, 16, p);
	}

	public boolean onTouchEvent(MotionEvent event) {
		super.onTouchEvent(event);
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			x = (int) event.getX();
			y = (int) event.getY();
			invalidate();
			return true;
		}
		return false;
	}
}